<template>
  <div class="drag-box" ref="dragBox">
    <slot></slot>
  </div>
</template>

<script>
  export default {
    name: 'dragImgUpload',
    data() {
      return {
        file: null,
        errText: '',
      }
    },
    computed: {

    },
    mounted() {
      // 阻止浏览器默认的拖拽时事件
      ['dragleave', 'drop', 'dragenter', 'dragover'].forEach(e => {
        this.preventDefaultEvent(e);
      });

      // 绑定拖拽支持
      this.addDropSupport();
      // 绑定粘贴支持
      this.addPasteSupport();
    },
    methods: {
      preventDefaultEvent(eventName) {
        document.addEventListener(eventName, function(e) {
          e.preventDefault();
        }, false)
      },
      // 粘贴
      addPasteSupport() {
        var _this = this;
        var drag = this.$refs.dragBox;
        var file = null;
        drag.addEventListener('paste', (e) => {
          //not for ie11  某些chrome版本使用的是event.originalEvent
          if(e.clipboardData || e.originalEvent) {
            var clipboardData = (event.clipboardData || event.originalEvent.clipboardData);
            var items = clipboardData.items;
            if(items[0].type.indexOf("image") !== -1) {
              //getAsFile() 此方法只是living standard firefox ie11 并不支持  
              file = items[0].getAsFile(); // 只需要最后一张
              
              e.preventDefault();

              _this.handleFileChange({
                files: [file]
              });
            }
          }
        })
      },
      // 拖拽
      addDropSupport() {
        var _this = this;
        var drag = this.$refs.dragBox;

        drag.addEventListener('drop', (e) => {
          e.preventDefault();
          // dataTransfer承载拖拽数据
          let fileList = e.dataTransfer.files

          if(fileList.length === 0) {
            return false
          }

          _this.handleFileChange({
            files: fileList
          });
        })
      },
      // Change
      handleFileChange(e) {
        this.$emit('onChange', e);
      },
    },
  }
</script>
